<template>
    <el-select v-model="inValue" v-on="$listeners" v-bind="$attrs">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
</template>

<script>
import { wifiModeDict } from '@/constant/dict';

export default {
    name: 'WiFiChannelWidth',
    props: {
        value: [String],
        wifiType: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            options: []
        };
    },
    computed: {
        inValue: {
            get: function () {
                return this.value;
            },
            set: function (newValue) {
                this.$emit('input', newValue);
            }
        }
    },
    methods: {
        async fetchData() {
            let result = '';

            let node = '';

            // 5G
            if (this.wifiType == wifiModeDict.WIFI5) {
                node = 'wifi_channel_list_5g';
            }
            // 6G
            else if (this.wifiType == wifiModeDict.WIFI6) {
                node = 'WIFI_CHANNEL_LIST_6G';
            }
            // 2.4G
            else {
                node = 'wifi_channel_list_24g';
            }

            const res = await this.$getNodeFromServer(...[node]);

            if (res && res[node]) {
                result = res[node];
            }

            if (result) {
                this.options = this.getChannelWidthOptions(result);
            }
        },

        /**
         * @description 获取信道宽度options
         * @param {*} arr WiFi信道数据
         */
        getChannelWidthOptions(arr) {
            try {
                const channel = JSON.parse(arr);
                const newArray = Object.entries(channel).map(([key], index, keyArr) => ({
                    value: parseInt(key.match(/\d+/)[0]) + 'M',
                    label:
                        keyArr
                            .slice(0, index + 1)
                            .map(([v]) => parseInt(v.match(/\d+/)[0]))
                            .join('/') + 'M'
                }));
                return newArray;
            } catch (error) {
                return [];
            }
        }
    },
    created() {
        this.fetchData();
    }
};
</script>

<style lang="less" scoped></style>
